package main

import (
	"log"
	"net/http"
	"os"
	"os/signal"
)

type helloHandler struct {
}

func main() {
	//hello world
	//http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request){
	//	w.Write([]byte("Hello world!"))
	//	name := r.FormValue("name")
	//	fmt.Println("name :",name)
	//
	//})
	//log.Println("Starting HTTP server...")
	//log.Fatal(http.ListenAndServe("localhost:4000",nil))

	//优雅的停止服务
	mux := http.NewServeMux()
	mux.Handle("/", &helloHandler{})

	server := &http.Server{
		Addr:    ":4000",
		Handler: mux,
	}
	//创建系统信号接收器
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	go func() {
		<-quit
		if err := server.Close(); err != nil {
			log.Fatal("Close server:", err)
		}
	}()

	log.Println("Starting HTTP server...")
	err := server.ListenAndServe()
	if err != nil {
		if err == http.ErrServerClosed {
			log.Print("Server closed under request")
		} else {
			log.Fatal("Server closed unexpected")
		}
	}
}

func (h helloHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	writer.Write([]byte("hello world!"))
}
